package cn.chinaunicom.sdsi.frm.workflow.task.dao.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.chinaunicom.sdsi.frm.workflow.bean.TaskVO;
import cn.chinaunicom.sdsi.frm.workflow.common.UtilDateTime;
import cn.chinaunicom.sdsi.frm.workflow.task.dao.ActTaskHistDao;

/**
 * 任务模块数据访问层组件
 * 
 * @author liyh
 * 
 */
@Repository("actTaskHistDao")
public class ActTaskHistDaoImpl implements ActTaskHistDao {

	private static final Log log = LogFactory.getLog(ActTaskHistDaoImpl.class);

	/**
	 * activiti历史信息查询组件
	 */
	private HistoryService historyService;

	/**
	 * 根据查询条件分页查询版本最新的流程定义
	 * 
	 * @param vo
	 *            查询实体
	 * @param firstResult
	 *            首条记录位置
	 * @param maxResults
	 *            页面大小
	 * @return 符合条件记录集合
	 */
	@Override
	public List<HistoricTaskInstance> listHasDone4Page(TaskVO vo, int firstResult, int maxResults) {

		HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery().includeProcessVariables();

		makeCondition(htiq, vo);
		log.debug("search Task use DAO, add condition done");

		return htiq.orderByHistoricTaskInstanceEndTime().desc().listPage(firstResult, maxResults);
	}

	/**
	 * 据传入参数查询符合条件的记录条数
	 * 
	 * @param vo
	 *            查询实体
	 * @return 符合条件总记录数
	 */
	@Override
	public long listFilteredCount(TaskVO vo) {
		HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();

		makeCondition(htiq, vo);
		log.debug("search Task use DAO, get FilteredCount ");

		return htiq.count();
	}

	/**
	 * 据查询条件查询全部记录的条数
	 * 
	 * @param vo
	 *            查询实体
	 * @return 全部记录数
	 */
	@Override
	public long listTotalCount(TaskVO vo) {
		// 普通查询不支持多人，暂只查第一岗位
		String userId = vo.getAssigneeIds()[0];
		HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();

		log.debug("search Task use DAO, get TotalCount ");

		return htiq.taskAssignee(userId).finished().count();
	}

	/**
	 * 复用拼装查询条件
	 * 
	 * @param query
	 * @return
	 */
	private HistoricTaskInstanceQuery makeCondition(HistoricTaskInstanceQuery query, TaskVO vo) {

		// 普通查询不支持多人，暂只查第一岗位
		String userId = vo.getAssigneeIds()[0];
		query = query.taskAssignee(userId).finished();

		// 依据流程标题查询
		if (!StringUtils.isBlank(vo.getTitle())) {
			String title = vo.getTitle();
			query = query.processVariableValueLike("title", "%" + title + "%");
		}
		// 依据环节名称查询
		if (!StringUtils.isBlank(vo.getLinkName())) {
			String linkName = vo.getLinkName();
			query = query.taskNameLike("%" + linkName + "%");
		}
		// 依据任务的创建时间查询
		if (!StringUtils.isBlank(vo.getCompleteTimeStart())) {
			Date endTimeStart = UtilDateTime.str2Date(vo.getCompleteTimeStart(), "yyyy-MM-dd");
			query = query.taskCompletedAfter(endTimeStart);
		}
		if (!StringUtils.isBlank(vo.getCompleteTimeEnd())) {
			Date endTimeEnd = UtilDateTime.str2Date(vo.getCompleteTimeEnd(), "yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endTimeEnd);
			calendar.add(Calendar.DATE, 1);
			query = query.taskCompletedBefore(calendar.getTime());
		}

		return query;
	}

	/**
	 * 据参数名返回参数值
	 * 
	 * @param task
	 *            历史任务
	 * @param varName
	 *            变量名称
	 * @return 索取的变量值
	 */
	@Override
	public Object parseVariable(HistoricTaskInstance task, String varName) {
		log.debug("search task vars: " + varName);

		return task.getProcessVariables().get(varName);
	}

	@Autowired
	public void setHistoryService(HistoryService historyService) {
		this.historyService = historyService;
	}

}
